<template>
  <x-dialog
    title="人员职称"
    :close-on-click-modal="false"
    :show.sync="visible"
    v-if="visible"
    lock-scroll
    append-to-body
    width="1000px"
    :footShow="false"
  >
    <el-button @click="handleAdd" style="float: right; margin-bottom: 10px" type="primary" v-if="!isDisabled"
      >新增</el-button
    >
    <x-table
      :data-source="tableData"
      size="mini"
      :pagination="pagination"
      :loading="loading"
      :row-key="'id'"
      :height="430"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column
        v-for="(item, index) in columnsTitle"
        :key="index"
        :prop="item.prop"
        :fixed="item.fixed"
        :show-overflow-tooltip="true"
        :width="item.width || 100"
        :label="item.label"
        :sortable="'custom'"
      >
        <template #default="scope">
          <span>{{ scope.row[item.prop] | emptyVal }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" :align="'center'" width="200" v-if="!isDisabled">
        <template #default="scope">
          <more-table-actions
            :permis-list="permissionsActions"
            :action-list="getActions(actions, scope.row)"
            :row="scope.row"
            @onActionClick="handleActions"
          />
        </template>
      </el-table-column>
    </x-table>

    <x-dialog
      width="30%"
      :title="titleInner"
      :show.sync="innerVisible"
      v-if="innerVisible"
      append-to-body
      :before-close="handleCloseInner"
      @onCancel="handleCloseInner"
      @onSubmit="handleSubmitInner"
      submitText="确定"
    >
      <el-form :model="params" :rules="rules" ref="params" label-position="top">
        <div class="form-components">
          <el-row :gutter="20">
            <x-col :span="24">
              <el-form-item label="职称名称" prop="name">
                <el-input v-model="params.name" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="24">
              <el-form-item label="职称分类" prop="category">
                <el-input v-model="params.category" placeholder="请输入" style="width: 100%" maxlength="20"></el-input>
              </el-form-item>
            </x-col>
            <x-col :span="24">
              <el-form-item label="职称级别" prop="rank">
                <el-input v-model="params.rank" placeholder="请输入" style="width: 100%" maxlength="100"></el-input>
              </el-form-item>
            </x-col>

            <x-col :span="24">
              <el-form-item label="职称扫描件" prop="scanPathList">
                <!-- 执照上传 -->
                <x-upload
                  ref="scanPathUpload"
                  tips=""
                  :edit-flag="true"
                  :limit="1"
                  :fileSize="20"
                  :old-file-list="params.scanPathList || []"
                  :file-type="['jpg', 'jpeg', 'png']"
                >
                </x-upload>
              </el-form-item>
            </x-col>
          </el-row>
        </div>
      </el-form>
    </x-dialog>
  </x-dialog>
</template>
<script>
  import {
    TableListMixin,
    QueryDictMixin,
    PermissionsMixin,
    selectDictLabel,
    cloneDeep,
    throttle
  } from '@package/utils'
  import { columnsTitle, actions } from '../config/certificateDialog.js'
  import {
    supplierStaffTitleUrl as listUrl,
    apiStaffTitleFindById,
    apiStaffTitleUpdate,
    apiStaffTitleAdd,
    apiStaffTitleDelete
  } from '../api/index.js'
  import { EnumApiCode } from '../../../../../../globalEnum.js'

  export default {
    components: {},
    mixins: [TableListMixin, QueryDictMixin, PermissionsMixin],
    props: {
      title: {
        type: String,
        default: ''
      },
      placeholder: {
        type: String,
        default: ''
      },
      isDisabled: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        activeName: 'first',
        listUrl,
        columnsTitle,
        actions,
        visible: false,
        dictKeys: ['system.preset'],
        searchParams: {
          staffId: '1152624610777235456'
        },
        params: {
          name: '',
          category: '',
          rank: '',
          scanPathList: []
        },
        rules: {
          name: [
            { required: true, message: '请输入职称名称', trigger: 'blur' },
            { min: 1, max: 20, trigger: 'blur' }
          ],
          category: [
            { required: true, message: '请输入', trigger: 'blur' },
            { min: 1, max: 20, trigger: 'blur' }
          ],
          rank: [
            { required: true, message: '请输入', trigger: 'blur' },
            { min: 1, max: 20, trigger: 'blur' }
          ],
          scanPath: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        innerVisible: false,
        titleInner: '新增',
        loading: false
      }
    },
    computed: {
      getActions() {
        return (actions) => {
          return actions.map((action) => {
            return action
          })
        }
      }
    },
    created() {
      this.initDictConfig()
    },
    methods: {
      selectDictLabel,
      handleActions({ key, data }) {
        switch (key) {
          case 'edit': // 修改
            this.getDetail(data.id)
            break
          case 'delete':
            this.handleDel(data.id)
            break
          case 'preview':
            console.log(data)
            // this.preview(data)
            break
          default:
            break
        }
      },
      handleDel(id) {
        this.$confirm('确认删除', '提示', {
          type: 'warning'
        })
          .then(() => {
            apiStaffTitleDelete(id).then(() => {
              this.loadData()
              this.$message({
                type: 'success',
                message: '操作成功'
              })
            })
          })
          .catch(() => {})
      },

      preview(row) {
        console.log('row: ', row)
        // const data = {
        //   flowCode: row.flowCode,
        //   flowName: row.flowName,
        //   formType: row.formType,
        //   formConf: row.formData
        // }
        // this.inner = true
        // this.$nextTick(() => {
        //   this.$refs.preview.init(data)
        // })
      },
      show(val) {
        this.searchParams.staffId = val
        this.visible = true
        this.queryParam = { ...this.searchParams }
        this.loadData()
      },
      handleReset() {
        this.queryParam = { ...this.searchParams }
        this.loadData()
      },
      handleClose() {
        this.selectData = []
        this.visible = false
      },
      // 多行选中
      handleSelectionChange(rows) {
        this.selectData = rows
      },
      // 弹窗确定
      handleSubmit() {
        if (this.selectData.length) {
          this.$emit('on-confirm', this.selectData)
          this.handleClose()
        } else {
          this.$message.error('请至少选择一条数据点击确定')
        }
      },
      handleAdd() {
        this.titleInner = '新增'
        this.params = {
          name: '',
          category: '',
          rank: '',
          scanPathList: [],
          scanPath: '',
          scanName: ''
        }
        this.innerVisible = true
      },
      async getDetail(id) {
        this.titleInner = '编辑'
        const { data } = await apiStaffTitleFindById(id)
        const { scanName, scanPath } = cloneDeep(data)
        this.params = Object.assign(this.params, cloneDeep(data))
        if (this.params.scanName && this.params.scanPath) {
          this.params.scanPathList = [{ fileName: scanName, filePath: scanPath }]
        } else {
          this.params.scanPathList = []
        }
        this.innerVisible = true
      },
      handleCloseInner() {
        this.$refs.params.resetFields()
        this.innerVisible = false
      },
      // 保存
      handleSubmitInner: throttle(function () {
        console.log
        this.$refs.params.validate(async (valid) => {
          if (valid) {
            const socialSecurityFile = this.$refs.scanPathUpload.fileList[0] || null
            if (socialSecurityFile?.response) {
              this.params.scanPathList = [
                {
                  fileName: socialSecurityFile.response.data.filePath,
                  filePath: socialSecurityFile.response.data.fileName
                }
              ]
            }
            const param = {
              staffId: this.searchParams.staffId,
              state: 0,
              ...this.params,
              scanPath: this.params.scanPathList.length > 0 ? this.params.scanPathList[0].filePath : '',
              scanName: this.params.scanPathList.length > 0 ? this.params.scanPathList[0].fileName : ''
            }
            try {
              this.loading = true
              // 人员证书
              const { code } = this.params.id ? await apiStaffTitleUpdate(param) : await apiStaffTitleAdd(param)
              if (code === EnumApiCode.Success) {
                this.$message.success(param.id ? this.$t('common.editSuccess') : this.$t('common.newSuccess'))
              }
            } finally {
              this.loading = false
              this.handleCloseInner()
              this.queryParam = { ...this.searchParams }
              this.loadData()
            }
          } else {
            return false
          }
        })
      }, 1000)
    }
  }
</script>
<style lang="scss" scoped>
  .search-btns {
    align-items: flex-end;
    display: flex;
    height: 70px;
  }
</style>
